package com.atgouwu.mall.order.controller;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import com.alibaba.fastjson.JSONObject;
import com.atgouwu.mall.common.exception.NoStockException;
import com.atgouwu.mall.common.utils.CryptoThirdSM4Tools;
import com.atgouwu.mall.common.utils.HttpUtils;
import com.atgouwu.mall.order.vo.OrderConfirmVo;
import com.atgouwu.mall.order.vo.OrderSubmitVo;
import com.atgouwu.mall.order.vo.SubmitOrderResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.atgouwu.mall.order.entity.OrderEntity;
import com.atgouwu.mall.order.service.OrderService;
import com.atgouwu.mall.common.utils.PageUtils;
import com.atgouwu.mall.common.utils.R;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单
 *
 * @author heran
 * @email sunlightcs@gmail.com
 * @date 2024-02-22 15:15:23
 */
@Api(tags = "订单")
@RestController
@RequestMapping("order/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = orderService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        OrderEntity order = orderService.getById(id);
        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderEntity order) {
        orderService.updateById(order);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        orderService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    //获取待提交订单
    @ApiOperation(value = "获取待提交订单")
    @GetMapping(value = "/api/toTrade")
    public R toTrade() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        return R.ok().put("data", confirmVo);
    }

    //提交订单
    @ApiOperation(value = "提交订单")
    @PostMapping(value = "/api/submitOrder")
    public R submitOrder(@RequestBody OrderSubmitVo vo) {
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            if (responseVo.getCode() == 0) { //下单成功(到支付页)
                return R.ok().put("data", responseVo);
            } else { //下单失败(回到订单确认页,重新确定订单信息)
                String msg = "下单失败";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "令牌订单信息过期，请刷新再次提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "库存锁定失败，商品库存不足";
                        break;
                }
                return R.error().put("msg", msg);
            }
        } catch (Exception e) {
            String message = e.getMessage();
            if (e instanceof NoStockException) {
                message = ((NoStockException) e).getMessage();
            }
            return R.error().put("msg", message);
        }
    }

    //分页获取已提交订单
    @ApiOperation(value = "分页获取已提交订单")
    @PostMapping("/api/listWithItem")
    public R listWithItem(@RequestBody Map<String, Object> params) {
        PageUtils page = orderService.queryPageWithItem(params);
        return R.ok().put("page", page);
    }

    //获取邮政物流
    @ApiOperation(value = "邮政物流")
    @GetMapping(value = "/api/postLogistics")
    public R postLogistics(@RequestParam("waybillNo") String waybillNo) throws Exception {
        Map<String, String> waybillNoMap = new HashMap<>();
        waybillNoMap.put("waybillNo", waybillNo);
        String waybillNoJson = JSONObject.toJSONString(waybillNoMap);
        String key = "c1NIU1hCOWttNVJIV1F5Tg==";
        String encryptStr = CryptoThirdSM4Tools.sm4Encrypt(waybillNoJson + key, key);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("content-type", "application/x-www-form-urlencoded");
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("apiCode", "040001");
        querys.put("senderNo", "1100167075974");
        querys.put("authorization", "SY2ZhYISgtIO9jYU");
        querys.put("timeStamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        querys.put("logitcsInterface", encryptStr);
        Map<String, String> bodys = new HashMap<String, String>();
        HttpResponse response = HttpUtils.doPost("https://api.ems.com.cn", "/amp-prod-api/f/amp/api/open", "POST", headers, querys, bodys);
        return R.ok().put("data", response);
    }

}
